import express from 'express';
import fs from 'fs';
import path from 'path';
import cors from 'cors';
import { fileURLToPath } from 'url';

const app = express();
const PORT = 3001;

// 获取当前文件目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 中间件
app.use(cors());
app.use(express.json());

// 配置文件路径
const CONFIG_DIR = path.join(__dirname, 'config');
const API_CONFIG_PATH = path.join(CONFIG_DIR, 'api-config.json');
const EXCHANGE_CONFIG_PATH = path.join(CONFIG_DIR, 'exchange-config.json');
const UI_PREFERENCES_PATH = path.join(CONFIG_DIR, 'ui-preferences.json');

// 确保配置目录存在
if (!fs.existsSync(CONFIG_DIR)) {
  fs.mkdirSync(CONFIG_DIR, { recursive: true });
}

// 创建默认配置文件
const createDefaultConfig = (configPath, defaultConfig) => {
  if (!fs.existsSync(configPath)) {
    fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2));
  }
};

// 设置默认配置
createDefaultConfig(API_CONFIG_PATH, { apiToken: 'KQBXL1S7R6B1Q152Z3F527L5' });
createDefaultConfig(EXCHANGE_CONFIG_PATH, {
  page_index: 1,
  res: 0,
  platforms: 'BUFF-YYYP',
  sort_by: 1,
  min_price: 1,
  max_price: 5000
});
createDefaultConfig(UI_PREFERENCES_PATH, {
  theme: 'light',
  pageSize: 20
});

// API配置相关路由
app.get('/api/config/api-config', (req, res) => {
  try {
    const config = JSON.parse(fs.readFileSync(API_CONFIG_PATH, 'utf8'));
    res.json(config);
  } catch (error) {
    console.error('读取API配置失败:', error);
    res.status(500).json({ error: '读取配置失败' });
  }
});

app.post('/api/config/api-config', (req, res) => {
  try {
    fs.writeFileSync(API_CONFIG_PATH, JSON.stringify(req.body, null, 2));
    res.json({ success: true });
  } catch (error) {
    console.error('保存API配置失败:', error);
    res.status(500).json({ error: '保存配置失败' });
  }
});

// Exchange配置相关路由
app.get('/api/config/exchange-config', (req, res) => {
  try {
    const config = JSON.parse(fs.readFileSync(EXCHANGE_CONFIG_PATH, 'utf8'));
    res.json(config);
  } catch (error) {
    console.error('读取Exchange配置失败:', error);
    res.status(500).json({ error: '读取配置失败' });
  }
});

app.post('/api/config/exchange-config', (req, res) => {
  try {
    fs.writeFileSync(EXCHANGE_CONFIG_PATH, JSON.stringify(req.body, null, 2));
    res.json({ success: true });
  } catch (error) {
    console.error('保存Exchange配置失败:', error);
    res.status(500).json({ error: '保存配置失败' });
  }
});

// UI偏好设置相关路由
app.get('/api/config/ui-preferences', (req, res) => {
  try {
    const preferences = JSON.parse(fs.readFileSync(UI_PREFERENCES_PATH, 'utf8'));
    res.json(preferences);
  } catch (error) {
    console.error('读取UI偏好设置失败:', error);
    res.status(500).json({ error: '读取配置失败' });
  }
});

app.post('/api/config/ui-preferences', (req, res) => {
  try {
    fs.writeFileSync(UI_PREFERENCES_PATH, JSON.stringify(req.body, null, 2));
    res.json({ success: true });
  } catch (error) {
    console.error('保存UI偏好设置失败:', error);
    res.status(500).json({ error: '保存配置失败' });
  }
});

// 启动服务器
app.listen(PORT, '0.0.0.0', () => {
  console.log(`配置服务器运行在 http://0.0.0.0:${PORT}`);
  console.log(`本地访问: http://localhost:${PORT}`);
  console.log(`外部访问: http://[你的IP地址]:${PORT}`);
});